package com.example.AsynTask;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.examplee.username.httpfrist_01.R;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class AsynTaskActivity extends AppCompatActivity {
    ImageView imageView;
    ProgressBar mprogressBar;
    static String Url="http://img.my.csdn.net/uploads/201504/12/1428806103_9476.png";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_asyn_task);
        imageView= (ImageView) findViewById(R.id.image_asyn);
        mprogressBar= (ProgressBar) findViewById(R.id.progressbar);
//        MyAsynTask task=new MyAsynTask();
//        task.execute();
//        设置传递进去的参数
        new MyAsynTask1().execute(Url);
    }
    class MyAsynTask1 extends AsyncTask<String,Void,Bitmap>{
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mprogressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            mprogressBar.setVisibility(View.GONE);
            imageView.setImageBitmap(bitmap);
        }
//开始真正的异步操作
        @Override
        protected Bitmap doInBackground(String... params) {
//            由于只有一个参数，所以只需取出它的下标为0 作为我们的URL
     /*
     * 1、获取传递进来的参数
     * */
            String url=params[0];
            Bitmap bitmap=null;
            URLConnection connection;//访问网络，获取网络对象
            InputStream inputStream;//获取输入,用于获取数据的输入流
            try {
                connection=new URL(url).openConnection();
                inputStream=connection.getInputStream();//获取输入流
                BufferedInputStream bis=new BufferedInputStream(inputStream);

                    Thread.sleep(3000);

//                通过decodeStream解析输入流
                bitmap= BitmapFactory.decodeStream(bis);
                inputStream.close();
                bis.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
//            返回bitmap
            return bitmap;
        }
    }
}
